let prefix = "/jzweb/trackDraw1";
let isDrawing = null;
let flag = false; // 标记是否正在进行抽签
let animationId;
let paging = 1;
let allPlayers = []; // 存储所有选手数据

$(function() {
    document.title = '竞赛管理平台';
    $('link[rel="shortcut icon"]').attr('href', `${'../../static/favicon.ico'}`)
    if(window.location.href.split('?')[1]) {
        $('.openPages').show()
    } else {
        $('.openPages').hide()
    }

    $.ajax({
        cache : true,
        type : "post",
        url : "/jzweb/stuSignUpCom/cbatchList",
        data:{
            types: 3,
        },
        error : function(request) {
            parent.layer.alert("Connection error");
        },
        success : function(data) {
            if (data.code == 0) {
                let str = '';
                data.data?.map(function (v,k){
                    str += `<option value="${v.id}">${v.name}</option>`
                })
                $("#cbatchName").html(str);
                load();
            } else {
                parent.layer.alert(data.msg)
            }
        }
    });

    $("#cbatchName").change(() => {
        reLoad()
    })
});

function columnsCreate() {
    return Array.from({ length: 3}, (_, i) => [
        {
            field: `unitName${i}`,
            title: '学校名称',
            align: 'center'
        },
        {
            field: `checkName1${i}`,
            title: '选手一',
            class: `player1-${i}`,
            align: 'center',
            formatter: (value, row, index) => value || '-'
        },
        {
            field: `checkName2${i}`,
            title: '选手二',
            class: `player2-${i}`,
            align: 'center',
            formatter: (value, row, index) => value || '-'
        }
    ]).flat();
}

function load() {
    $('#exampleTable').bootstrapTable({
        method: 'get',
        url: '/jzweb/trackDraw/trackList1',
        iconSize: 'outline',
        toolbar: '#exampleToolbar',
        theadClasses: "thead-dark",
        striped: true,
        dataType: "json",
        pagination: true,
        singleSelect: false,
        pageSize: 999999,
        pageNumber: 1,
        showColumns: false,
        sidePagination: "server",
        queryParamsType: "",
        paginationDetail: false,
        pageList: [15, 25, 50, 100],
        queryParams: function(params) {
            paging = params.pageNumber;
            return {
                current: params.pageNumber,
                size: params.pageSize,
                cbatchId: $('#cbatchName').val()
            };
        },
        responseHandler: function(res) {
            if (res.code !== '0') {
                layer.msg(res.msg);
                return false;
            }
            let { data } = res;
            allPlayers = data; // 存储所有选手数据
            let list = dataCreate(data);
            isDrawing = data[0]?.hasDraw;
            return {
                "rows": list,
                "total": res.data.total,
            };
        },
        columns: columnsCreate()
    });
}

function reLoad() {
    $('#exampleTable').bootstrapTable('refresh');
}

/**
 * 数据处理
 * value 需要处理得数据
 * */
function dataCreate(value){
    return value.map(({ trackDrawDOList }) =>
        (trackDrawDOList || []).reduce((mappedItem, { unitName, name1, name2, name3, name4 }, index) => {
            mappedItem[`unitName${index}`] = unitName;

            // 创建选手数组并过滤空值
            const players = [name1, name2, name3, name4].filter(p => p && p.trim());
            mappedItem[`_players${index}`] = players; // 存储选手数组

            // 初始化显示
            mappedItem[`checkName1${index}`] = players[0] || '';
            mappedItem[`checkName2${index}`] = players[1] || '';

            return mappedItem;
        }, {})
    );
}
const importExcelModelFile = () => {
    layer.open({
        type: 1, // page 层类型
        area: ['500px', '300px'],
        title: '导入',
        shade: 0.6, // 遮罩透明度
        shadeClose: true, // 点击遮罩区域，关闭弹层
        maxmin: true, // 允许全屏最小化
        anim: 0, // 0-6 的动画形式，-1 不开启
        content: `
        <div class="layui-upload-drag" style="display: block;height: 100%;display: flex;flex-direction: column;align-items: center;justify-content: center;" id="ID-upload-demo-drag">
          <i class="layui-icon layui-icon-upload"></i> 
          <div>点击上传，或将文件拖拽到此处</div>
          <div class="layui-hide" id="ID-upload-demo-preview">
          </div>
        </div>
        `
    });

    layui.use(function(){
        const upload = layui.upload;
        const $ = layui.$;
        // 渲染
        upload.render({
            elem: '#ID-upload-demo-drag',
            accept: 'file', // 普通文件
            url: `/jzweb/trackDraw/importExcelTrackDraw2?cbatchId=${$('#cbatchName').val()}`, // 实际使用时改成您自己的上传接口即可。
            done: function(res){
                console.log(res)
                if(res.code * 1) {
                    layer.msg(res.msg);
                    return
                }
                layer.msg('导入成功');
                layer.closeAll()
                reLoad()
            }
        });
    });
}


/**
 * 导出
 */
function downExcelModelFile() {
    layer.confirm('您确定要导出吗？', {
        btn1: function(index) {
            if (!isDrawing) {
                layer.msg('请先完成抽签');
                layer.close(index);
                return;
            }
            try {
                window.location.href = `/jzweb/trackDraw/downloadImportTemplate1?cbatchId=${$('#cbatchName').val()}`;
                layer.close(index);
            } catch (e) {
                layer.msg('导出失败');
            }
        }
    });
}

/**
 * 下载导入模板
 */
const downloadExcelModelFile = () => {
    window.location.href = "/jzweb/trackDraw/exportTrackDraw1";
}

const openPage =() => {
    window.open('/jzweb/trackDraw1',"_blank")
}

function trackDrawCreate() {
    $.ajax({
        type: "get",
        url: `/jzweb/trackDraw/list1?current=${paging}&size=15&cbatchId=${$('#cbatchName').val()}`,
        async: false,
        error: function(request) {
            parent.layer.alert(request);
        },
        success: function(res) {
            if (res.code === '0') {
                flag = false; // 立即停止标志
                cancelAnimationFrame(animationId);
                let data = dataCreate(res.data);
                $('#exampleTable').bootstrapTable('load', data);
                let options = $('#exampleTable').bootstrapTable('getOptions');
                options.totalRows = res.data.total;
                $('#exampleTable').bootstrapTable('refreshOptions', options);
                layer.msg('抽签完毕');
            } else {
                parent.layer.alert(res.msg);
            }
        }
    });
}

/**
 * 开始抽签
 */
const drawBButton = () => {
    let index = layer.confirm('确定开始抽签？', {
        btn: ['确定', '取消']
    }, function() {
        let rows = $('#exampleTable').bootstrapTable('getData');
        if(!rows.length) {
            return layer.msg('请导入学校名称');
        }
        if (flag) {
            return layer.msg('抽签中');
        }
        flag = true;
        animateNumbers();
        layer.close(index);
    });
}


/**
 * 停止抽签
 */
const stopButton = () => {
    let index = layer.confirm('确定停止抽签？', {
        btn: ['确定', '取消']
    }, function() {
        if (flag) {
            trackDrawCreate(); // 获取抽签结果
        } else {
            if (isDrawing) {
                layer.msg('抽签已完成');
                return;
            }
            layer.msg('请先完成抽签');
        }
        layer.close(index);
    });
}

function animateNumbers() {
    if (!flag) {
        cancelAnimationFrame(animationId);
        return;
    }

    let rows = $('#exampleTable').bootstrapTable('getData');
    if (rows.length === 0) return layer.msg('暂无选手信息');

    // 更新DOM - 使用当前学校当前组内的名字进行抽签
    $('#exampleTable tbody tr').each(function(rowIndex) {
        const rowData = rows[rowIndex];

        // 处理每个列组（0,1,2）
        for (let i = 0; i < 3; i++) {
            const players = rowData[`_players${i}`] || [];

            if (players.length > 0) {
                // 随机打乱当前组内的选手数组
                const shuffledPlayers = [...players];
                shuffleArray(shuffledPlayers);

                // 更新显示
                $(this).find(`.player1-${i}`).text(shuffledPlayers[0] || '-');
                $(this).find(`.player2-${i}`).text(shuffledPlayers[1] || '-');
            }
        }
    });

    animationId = requestAnimationFrame(animateNumbers);
}

// 辅助函数：打乱数组
function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
}